package com.edu.learning.concurrent;

import com.edu.learning.utils.LearnThreadFactory;

import java.util.concurrent.*;

/**
 * @author ll
 * @Date 2017/10/30 16:47
 */
public class FixedThreadPoolHelper {

    private static final FixedThreadPoolHelper INSTANCE = new FixedThreadPoolHelper();

    /**
     * 线程数量大小
     *
     * ((线程等待时间+线程CPU时间 ) / 线程CPU时间 ) * CPU数目  //((0.5+1.5)/0.5)*8=32
     */
    private static final int DEFAULT_THREAD_MAX = ((1 + 2) * 2) * Runtime.getRuntime().availableProcessors();

    public static ExecutorService getExecutorService(String namePrefix, boolean daemon) {
        final ThreadFactory threadFactory =
                LearnThreadFactory.create(namePrefix, daemon);
        ExecutorService service = new ThreadPoolExecutor(DEFAULT_THREAD_MAX, DEFAULT_THREAD_MAX, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());
        return service;
    }

    public int getDefaultThreadMax() {
        return DEFAULT_THREAD_MAX;
    }

    private FixedThreadPoolHelper() {
    }

    public static FixedThreadPoolHelper getInstance() {
        return INSTANCE;
    }
}
